<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">营业分类汇总</div> -->
    <QueryForm
      v-model="filters"
      :show-qk="showQk"
      :query-form-config="queryFormConfig"
      @handleQuery="getDataList"
    >
      <template #btns>
        <el-button v-preventReClick type="primary" @click="exportExcel">{{
          translate("export")
        }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="tableRef"
      :data="list"
      border
      fit
      show-summary
      :summary-method="getSummaries"
      :header-row-class-name="'table-header'"
      class="doumee-element-table table_tj"
    >
      <el-table-column
        prop="businessName"
        :label="translate('consumCate')"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="venueName"
        align="center"
        :label="translate('venue')"
        min-width="200"
      />
      <el-table-column :label="translate('yysr')" align="center">
        <el-table-column
          prop="cash"
          :label="translate('xj')"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="member"
          :label="translate('hyk')"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="weChat"
          :label="translate('wx')"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="aliPay"
          :label="translate('zfb')"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="transfer"
          :label="translate('transferMoney')"
          align="center"
          min-width="200"
        />
      </el-table-column>
      <el-table-column
        prop="sum"
        :label="translate('total')"
        min-width="200"
        align="center"
      />
    </el-table>
    <!-- <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="cur_page"
        :hide-on-single-page="true"
        @current-change="getDataList"
      />
    </div> -->
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
// import { parseTime } from '@/utils/index'
import { venueList, businessClassify } from '@/api'
import { getFMdate } from '@/utils/index'
import { queryFormConfig } from './config'
export default {
  name: 'BusinessStatisticssSummary',
  data() {
    return {
      queryFormConfig,
      showQk: false,
      venueList: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },

      total: 0,
      dateIndex: 1,
      weekList: [],
      filters: {
      }
    }
  },
  created() {
    this.setDate(new Date())
    this.getVenueList()
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.translate('total')
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = '-'
        }
      })

      for (var key = 1; key <= sums.length; key++) {
        const number = sums[key]
        if (!isNaN(number)) {
          sums[key] = parseFloat(number).toFixed(2)
        }
      }
      return sums
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: { flag: '0' }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.venueList = res.recordList
          const arr = res.recordList
          this.queryFormConfig.formItems[0].options = arr
          this.getDate(1)
          this.getDataList()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getDataList() {
      const param = this.filters
      if (param.time && param.time.length > 0) {
        param.startTime = param.time[0]
        param.endTime = param.time[1]
      } else {
        param.startTime = ''
        param.endTime = ''
      }
      businessClassify({
        param
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getDate(e) {
      this.dateIndex = e
      if (e === 1) {
        // this.filters.startTime = parseTime(new Date()).slice(0, 10)
        // this.filters.endTime = parseTime(new Date()).slice(0, 10)
        this.$set(this.filters, 'time', [getFMdate(-1, '-').slice(0, 10), getFMdate(-1, '-').slice(0, 10)])
      } else if (e === 2) {
        // this.filters.startTime = this.weekList[0].value
        // this.filters.endTime = this.weekList[6].value
        this.$set(this.filters, 'time', [this.weekList[0].value, this.weekList[6].value])
      } else {
        var date = new Date()
        var year = date.getFullYear() + '-'
        var month = this.calculation(date.getMonth() + 1) + '-'
        var day = new Date(date.getFullYear(), date.getMonth() + 1, 0)
        // this.filters.startTime = year + month + '01'
        // this.filters.endTime = year + month + day.getDate()
        this.$set(this.filters, 'time', [year + month + '01', year + month + day.getDate()])
      }
    },
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = [this.translate('z7'), this.translate('z1'), this.translate('z2'), this.translate('z3'), this.translate('z4'), this.translate('z5'), this.translate('z6')][date.getDay()]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    setDate(date) {
      var week = date.getDay() - 1
      if (week === -1) {
        week = 6
      }
      date = this.addDate(date, week * -1)
      this.currentDate = new Date(date)
      const arr = []
      for (var i = 0; i < 7; i++) {
        arr[i] = this.formatDate(i === 0 ? date : this.addDate(date, 1))
      }
      this.weekList = arr
    },
    exportExcel() {
      /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(document.querySelector('.doumee-element-table'), xlsxParam)
      /* get binary string as output */
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      // 设置当前日期
      const time = new Date()
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const day = time.getDate()
      const filename = year + '' + month + '' + day + this.translate('yyfltj') + '.xlsx'
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    },
    // 清空筛选项
    clearFilters() {
      this.filters = {}
      this.getDataList()
    }
  }
}
</script>
<style scoped lang="scss">
.tabDate {
  display: flex;
  div {
    background-color: #f5f7fa;
    color: #111111;
    display: inline-block;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    box-sizing: border-box;
    cursor: pointer;
    &:nth-of-type(2) {
      border-left: 1px solid #dcdfe6;
      border-right: 1px solid #dcdfe6;
    }
    &.on {
      color: #fff;
      background-color: #435ebe;
    }
  }
}
</style>

